package cn.iocoder.yudao.module.spot.controller.admin;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.spot.dto.PackDto;
import cn.iocoder.yudao.module.spot.dto.SpotDto;
import cn.iocoder.yudao.module.spot.entity.CollectionResponse;
import cn.iocoder.yudao.module.spot.entity.PackEntity;
import cn.iocoder.yudao.module.spot.entity.SpotEntity;
import cn.iocoder.yudao.module.spot.service.SpotService;
import cn.iocoder.yudao.module.spot.vo.PackVo;
import cn.iocoder.yudao.module.spot.vo.SpotVo;
import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Api(tags = "A管理后台 - Spot")
@RestController
@RequestMapping("/spot")
@Validated
public class SpotController {
    @Resource
    private SpotService spotService;

    @PostMapping("/getlist")
    @ApiOperation("获取图斑列表信息")
    public CommonResult<CollectionResponse<SpotVo>> getlist(@RequestBody SpotDto spotDto) {
        SpotEntity entity = SpotDto.toSpotEntity(spotDto);
        List<SpotEntity> entities = null;
        int count = 0;
        count = spotService.count(entity);
        entities = spotService.getListByParams(spotDto.getPageSize(),spotDto.getPageNum(),entity);
        List<SpotVo> vos = entities.stream().map(spotEntity -> {
            SpotVo vo = SpotVo.fromSpotEntity(spotEntity);
            return vo;
        })
        .collect(Collectors.toList());

        CollectionResponse<SpotVo> collectionResponse = new CollectionResponse<>();
        collectionResponse.setCount(count);
        collectionResponse.setData(vos);
        return success(collectionResponse);
    }

    @PostMapping("/pack")
    @ApiOperation("下载图斑信息")
    public CommonResult<String> doPack(@RequestBody PackDto packDto){
        PackEntity entity = PackDto.toPackEntity(packDto);
        List<PackEntity> entities = spotService.getPackList(entity);
        if(entities == null){
            return success("查询无信息");
        }
        List<PackVo> vos = entities.stream().map(packEntity -> {
            PackVo vo = PackVo.fromPackEntity(packEntity);
            vo.setSsx(packEntity.getSmc()+packEntity.getDsmc()+packEntity.getQxmc());
            return vo;
        })
        .collect(Collectors.toList());
        boolean flag = pack(vos);
        if(!flag){
            return success("下载失败");
        }
        return success("下载成功");
    }
    private boolean pack(List<PackVo> vos){
        String filename = "D:\\write.xlsx";
        EasyExcel.write(filename,PackVo.class).sheet("图斑信息").doWrite(vos);
        return true;
    }

}
